<template>
  <NModal v-model:show="visible" :title="title" :mask-closable="false" transform-origin="center" preset="card" @after-leave="closeDrawer" class="w-800px">
    <NScrollbar class="h-400px pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NGrid responsive="screen" item-responsive>
          <NFormItemGi span="24 m:12" label="资源类型" path="category">
            <NRadioGroup v-model:value="model.category">
              <NRadio v-for="item in resourceCategoryOptions" :key="item.value" :value="item.value">
                {{item.label}}
              </NRadio>
            </NRadioGroup>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="资源名称" path="title">
            <NInput v-model:value="model.title" placeholder="请输入资源名称" clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="路由名称" path="name">
            <NInput v-model:value="model.name" placeholder="请输入路由名称" clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="路由路径" path="path">
            <NInput v-model:value="model.path" placeholder="请输入路由路径" disabled />
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="图标类型" path="iconType">
            <NRadioGroup v-model:value="model.iconType">
              <NRadio v-for="item in iconOptions" :key="item.value" :value="item.value">
                {{item.label}}
              </NRadio>
            </NRadioGroup>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="图标" path="icon">
            <template v-if="model.iconType === '1'">
              <NInput v-model:value="model.icon" placeholder="请输入图标" class="flex-1">
                <template #suffix>
                  <SvgIcon v-if="model.icon" :icon="model.icon" class="text-icon" />
                </template>
              </NInput>
            </template>
            <template v-if="model.iconType === '2'">
              <NSelect
                v-model:value="model.icon"
                placeholder="请选择图标"
                :options="localIconOptions"
              />
            </template>
          </NFormItemGi>

          <NFormItemGi v-if="model.category === 'MENU'" span="24 m:12" label="页面组件" path="component">
            <NInput v-model:value="model.component" placeholder="请输入页面组件"/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="上级菜单" path="parentId">
            <NTreeSelect v-model:value="model.parentId" label-field="title" key-field="id" :options="treeOptions"
                         placeholder="请选择上级菜单" default-expand-all clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="排序" path="sortCode">
            <NInputNumber class="w-100%" v-model:value="model.sortCode" placeholder="请输入排序" clearable/>
          </NFormItemGi>

        </NGrid>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">取消</NButton>
        <NButton type="primary" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'ResourceEditModal'
});

import {computed, reactive, watch,toRefs} from "vue";
import type { SelectOption } from 'naive-ui';
import {resourceCategoryOptions} from "@/constants/common";
import {useFormRules, useNaiveForm} from "@/hooks/common/form";
import { getLocalIcons } from '@/utils/icon';
import {getRoutePathByRouteName} from './shared';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { resourceList,resourceDetail } from '@/service/api/resource-api'

export type OperateType = NaiveUI.TableOperateType;
const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule} = useFormRules();

interface Props {
  // 操作类型
  operateType: OperateType;
  // 编辑资源的数据
  rowData?: number;
}
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const props = defineProps<Props>();
const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: '新增资源',
    edit: '编辑资源'
  };
  return titles[props.operateType];
});

const state = reactive({
  treeOptions: [] as Api.SystemManage.ResourceInfo[],
  iconOptions:[
    {label: 'iconify图标', value: '1'},
    {label: '本地图标', value: '2'}
  ] as  CommonType.Option[],
})
// 转为ref后解构
const {treeOptions,iconOptions} = {...toRefs(state)};

const localIcons = getLocalIcons();
const localIconOptions = localIcons.map<SelectOption>(item => ({
      label: () => (
        <div class="flex-y-center gap-16px">
        <SvgIcon localIcon={item} class="text-icon" />
      <span>{item}</span>
      </div>
  ),
  value: item
}));

// 监听打开窗口时，逻辑处理
watch(visible, () => {
  if (visible.value) {
    // 清空表单
    Object.assign(model, createDefaultModel());
    // 获取上级菜单
    getResourceSelectTree()
    if (props.operateType === 'edit' && props.rowData) {
      // 查询职位详情
      getResourceDetail();
    }
    restoreValidation();
  }
});
async function getResourceSelectTree(){
  const {data} = await resourceList();
  if (Array.isArray(data)) {
    state.treeOptions = data
  }

}
// form表单字段
type Model = Pick<Api.SystemManage.ResourceInfo, |'parentId'| 'name' | 'title' | 'category'|'menuType'|'path'| 'component' |'icon'|'iconType'| 'sortCode' >;
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    parentId:null,
    name: '',
    title: '',
    menuType: null,
    path:'',
    component:'',
    category: 'MENU',
    icon:'',
    iconType:'1',
    sortCode:99
  }
}
// 排除非必填
type RuleKey = Exclude<keyof Model,  |'component'|'icon'|'iconType'>;
// 必填项
const rules: Record<RuleKey, App.Global.FormRule> = {
  parentId: defaultRequiredRule,
  menuType: defaultRequiredRule,
  title: defaultRequiredRule,
  name: defaultRequiredRule,
  path: defaultRequiredRule,
  sortCode:defaultRequiredRule,
  category: defaultRequiredRule
};

function handleUpdateRoutePathByRouteName() {
  if (model.name) {
    model.path = getRoutePathByRouteName(model.name);
  } else {
    model.path = '';
  }
}

watch(
  () => model.name,
  () => {
    handleUpdateRoutePathByRouteName();
  }
);

// 查询资源详情
async function getResourceDetail() {
  if (props.rowData != undefined) {
    const {data} = await resourceDetail(props.rowData)
    Object.assign(model, data);
  }
}

// 取消、关闭弹框
function closeDrawer() {
  visible.value = false;
}

// 提交
async function handleSubmit() {
  // 必填项校验
  await validate();
  const params = getSubmitParams();
  console.log('params: ', params);
  // request
  window.$message?.success('操作成功');
  // 取消、关闭弹框
  closeDrawer();
  // 调用父组件事件
  emit('submitted');
}

function getSubmitParams() {
  const {...params} = model;
  return params;
}
</script>

<style scoped>

</style>
